package demo02;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class FileUploadServer {
    public static void main(String[] args) {
        try (ServerSocket serverSocket = new ServerSocket(8888);
                FileOutputStream fileOutputStream = new FileOutputStream("file\\download\\墩墩土.jpg")) {
            Socket socket = serverSocket.accept();
            InputStream inputStream = socket.getInputStream(); // 服务器端接收客户端发送的数据
            File file = new File("file\\download");
            if (!file.exists()) {
                file.mkdirs(); // 如果文件夹不存在，则创建文件夹
            }
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len); // 服务器端将数据上传到服务器（用文件夹模拟服务器）
            }
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("上传成功！".getBytes()); // 服务器端向客户端回写提示信息
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
